package cn.likole.oj.module;

import cn.likole.oj.bean.Problem;
import cn.likole.oj.bean.User;
import cn.likole.oj.service.ProblemService;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.QueryResult;
import org.nutz.dao.pager.Pager;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.annotation.*;
import org.nutz.mvc.filter.CheckSession;
import org.nutz.plugins.apidoc.annotation.Api;

import javax.servlet.http.HttpSession;

/**
 * Created by likole on 7/26/18.
 */
@IocBean
@At("/problem")
@Filters(@By(type = CheckSession.class, args = {"uid", "/"}))
@Api(name = "问题模块",description = "获取问题列表,获取问题")
public class ProblemModule {

    @Inject
    protected Dao dao;

    @Inject
    private ProblemService problemService;

    @At
    public Object getProblem(@Param("id") int id, HttpSession session){
        NutMap re=new NutMap();
        User user=dao.fetch(User.class, (int)session.getAttribute("uid"));

        if(user.getStage()==0){
            //第一阶段
            Problem problem= problemService.availableInTutorial(id,user);
            if(problem!=null) return re.setv("ok",true).setv("problem",problem);
            return re.setv("ok",false).setv("msg","用户所在章节无此题目");
        }else {
            //第二阶段
        }
        return re.setv("ok",false);
    }

    @At
    @Api(name = "获取问题列表",description ="search普通搜索;full-search高级搜索(多关键词以空格分开)" )
    @Ok("json:{locked:'valid'}")
    public Object problemList(@Param("search") String search,@Param("full-search") String fullsearch, @Param("..")Pager pager){
        Cnd cnd=Cnd.where("valid","=",1);
        if(!Strings.isBlank(search)){
            SqlExpressionGroup e1=Cnd.exps("title","like","%"+search+"%").or("source","like","%"+search+"%");
            cnd.and(e1);
        }else if(!Strings.isBlank(fullsearch)){
            fullsearch =fullsearch.replace(" ","%");
            SqlExpressionGroup e1=Cnd.exps("title","like","%"+fullsearch+"%").or("source","like","%"+fullsearch+"%").or("description","like","%"+fullsearch+"%");
            cnd.and(e1);
        }
        QueryResult qr = new QueryResult();
        qr.setList(dao.query(Problem.class, cnd, pager));
        pager.setRecordCount(dao.count(Problem.class, cnd));
        qr.setPager(pager);
        return qr;
    }

}
